﻿using DoNet.Handlers.Commands;
using DoNet.Common.Enums;
using DoNet.Common.Helpers;
using DoNet.Email.Entity;
using DoNet.Quartz.Jobs.Common;
using DoNet.System.IServices;
using DoNet.System.Models;
using MediatR;
using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using System.Diagnostics;

namespace DoNet.Quartz.Jobs
{
    /// <summary>
    /// 处理远程接口url的定时任务
    /// </summary>
    [DisallowConcurrentExecution]
    public class HttpResultfulJob : IJob
    {
        private readonly ITaskManagerService taskManagerService;
        private IMediator mediator;
        public HttpResultfulJob(ITaskManagerService _taskManagerService, IMediator _mediator)
        {
            taskManagerService = _taskManagerService;
            mediator = _mediator;
        }

        /// <summary>
        /// 执行远程接口url的定时任务
        /// </summary>
        /// 
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            var trigger = (context as JobExecutionContextImpl)?.Trigger as AbstractTrigger;
            if (trigger != null)
            {
                string httpMessage = "";
                TaskManager taskManager = await taskManagerService.GetByWhereAsync("Id=@PrimaryKey and GroupName=@GroupName", new { PrimaryKey = trigger.Name, GroupName = trigger.Group });
                if (taskManager != null)
                {
                    FileQuartz.InitTaskJobLogPath(taskManager.Id);
                    string msg = $"开始时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")}";
                    //记录任务执行记录
                    await taskManagerService.RecordRunAsync(taskManager.Id, JobAction.开始, true, msg);
                    if (string.IsNullOrEmpty(taskManager.JobCallAddress) || taskManager.JobCallAddress == "/")
                    {
                        FileQuartz.WriteErrorLog($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")}未配置任务地址,");
                        await taskManagerService.RecordRunAsync(taskManager.Id, JobAction.结束, false, "未配置任务地址");
                    }
                    else
                    {
                        try
                        {
                            Uri uri = new Uri(taskManager.JobCallAddress);
                            string baseAddress = uri.GetLeftPart(UriPartial.Authority); // 这会返回 http://www.example.com:80 (如果端口是80，则不显示端口)
                            //Console.WriteLine(baseAddress); // 输出: http://www.example.com 或 http://www.example.com:80（如果端口不是80）
                            string endpoint = taskManager.JobCallAddress.Replace(baseAddress, "");
                            Dictionary<string, string> header = new Dictionary<string, string>();

                            using (var httpClient = new HttpClientHelper(baseAddress))
                            {
                                if (!string.IsNullOrEmpty(taskManager.JobCallParams))
                                {
                                    httpMessage = await httpClient.PostStringAsync(endpoint, taskManager.JobCallParams, header) ?? string.Empty;
                                }
                                else
                                {
                                    httpMessage = await httpClient.GetAsync<string>(endpoint, header) ?? string.Empty;
                                }
                            }
                            stopwatch.Stop();
                            string resume = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒\r\n";
                            await taskManagerService.RecordRunAsync(taskManager.Id, JobAction.结束, true, resume, $"消息:{httpMessage ?? "OK"}");
                            if ((NoticeType)taskManager.SendMail == NoticeType.All)
                            {
                                if (!string.IsNullOrEmpty(taskManager.EmailAddress))
                                {
                                    List<string> recipients = new List<string>();
                                    recipients = taskManager.EmailAddress.Split(",").ToList();
                                    var mailBodyEntity = new MailBodyEntity()
                                    {
                                        Body = resume + "\n\r请勿直接回复本邮件！",
                                        Recipients = recipients,
                                        Subject = taskManager.TaskName,
                                    };
                                    SendMailCommand sendMailCommand = new SendMailCommand(mailBodyEntity);
                                    await mediator.Send(sendMailCommand);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            stopwatch.Stop();
                            string resume = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒\r\n";
                            taskManagerService.RecordRun(taskManager.Id, JobAction.结束, true, resume, ex.Message);
                            FileQuartz.WriteErrorLog(ex.Message);
                            if ((NoticeType)taskManager.SendMail == NoticeType.Error || (NoticeType)taskManager.SendMail == NoticeType.All)
                            {
                                if (!string.IsNullOrEmpty(taskManager.EmailAddress))
                                {
                                    List<string> recipients = new List<string>();
                                    recipients = taskManager.EmailAddress.Split(",").ToList();
                                    var mailBodyEntity = new MailBodyEntity()
                                    {
                                        Body = resume + ex.Message + "\n\r请勿直接回复本邮件!",
                                        Recipients = recipients,
                                        Subject = taskManager.TaskName,
                                    };
                                    SendMailCommand sendMailCommand = new SendMailCommand(mailBodyEntity);
                                    await mediator.Send(sendMailCommand);
                                }
                            }
                        }
                    }
                }
                else
                {
                    FileQuartz.WriteErrorLog($"任务不存在");
                }
            }
        }
    }
}
